package com.whmnx.my.ui.viewmodel;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableInt;
import androidx.databinding.ObservableList;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.qcloud.ugckit.utils.ToastUtil;
import com.whmnx.base.bean.BaseBean;
import com.whmnx.base.bean.OrderDetailBean;
import com.whmnx.base.bean.OrderListBean;
import com.whmnx.base.bean.PayBean;
import com.whmnx.base.bean.PayResult;
import com.whmnx.base.bean.WeixinBean;
import com.whmnx.base.constants.Constants;
import com.whmnx.base.constants.EventConstants;
import com.whmnx.base.http.CallBack;
import com.whmnx.base.http.HttpClient;
import com.whmnx.base.utils.UItils;
import com.whmnx.base.view.CommonDialog2;
import com.whmnx.my.BR;
import com.whmnx.my.R;
import com.whmnx.my.ui.activity.AppraiseActivity;
import com.whmnx.my.ui.activity.AppraiseXiangActivity;
import com.whmnx.my.ui.activity.RequestActivity;
import com.whmnx.my.ui.activity.WuLiuActivity;
import com.whmnx.my.ui.fragment.MyOrderDetailsFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.ItemViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

/**
 * author : huang
 * date   : 2020/10/20 0020 11:58
 * version: 1.0
 * @author Administrator
 */
public class OrderItemViewModel2 extends ItemViewModel {

    private  String order_id1;
    public  String order_id;
    public ObservableField<String> Order_StateDesc = new ObservableField<>("");
    public ObservableField<String> Order_OrderNo = new ObservableField<>("");
    public ObservableField<String> Order_State = new ObservableField<>("");

    public ObservableField<String> Order_pay = new ObservableField<>("");
    public ObservableInt viewVisibility = new ObservableInt(View.GONE);
    public ObservableInt view2Visibility = new ObservableInt(View.VISIBLE);
    private OrderModel viewModel;
    private ViewPagerItemViewModel viewPagerItemViewModel;
    private OrderListBean orderListBean;
    private Disposable subscribe;


    public OrderItemViewModel2(@NonNull OrderModel viewModel,ViewPagerItemViewModel viewPagerItemViewModel, OrderListBean productListBean) {
        super(viewModel);
        this.viewModel = viewModel;
        this.viewPagerItemViewModel = viewPagerItemViewModel;
        this.orderListBean = productListBean;
        order_id = productListBean.getOrder_OrderNo();
        order_id1 = productListBean.getOrder_Id();


        //Order_StateDesc
        Order_StateDesc.set(productListBean.getOrder_StateDesc());
        //最右边的按钮
      //  Order_pay.set(UItils.getOrderState(productListBean.getOrder_State()));
        Order_State.set(UItils.getOrderState(productListBean.getOrder_State()));
        //0待支付
        if (productListBean.getOrder_State().equals("0")){
            viewVisibility.set(View.VISIBLE);
            view2Visibility.set(View.VISIBLE);
            Order_State.set("取消订单");
            Order_pay.set("待支付");
        }else if (productListBean.getOrder_State().equals("1")){
            viewVisibility.set(View.GONE);
            Order_State.set("申请退款");
        }else if (productListBean.getOrder_State().equals("2")){
            viewVisibility.set(View.VISIBLE);
            view2Visibility.set(View.VISIBLE);
            Order_State.set("申请退货");
            Order_pay.set("确认收货");
        }else if (productListBean.getOrder_State().equals("3")){
            viewVisibility.set(View.VISIBLE);
            view2Visibility.set(View.INVISIBLE);
            Order_pay.set("去评价");
        }else if (productListBean.getOrder_State().equals("5") || productListBean.getOrder_State().equals("11")){  //5退款/售后  11申请退货
            viewVisibility.set(View.GONE);  //Order_pay
            view2Visibility.set(View.VISIBLE);
            Order_State.set("查看详情");
            Order_pay.set("填写物流");
        }else if (productListBean.getOrder_State().equals("-1") || productListBean.getOrder_State().equals("4")){  //已完成 状态是 4
            viewVisibility.set(View.INVISIBLE);
            view2Visibility.set(View.INVISIBLE);
        }else if (productListBean.getOrder_State().equals("12") ){  //12同意退货
            viewVisibility.set(View.VISIBLE);
            view2Visibility.set(View.VISIBLE);
            Order_State.set("查看详情");
            Order_pay.set("填写物流");
        }else if (productListBean.getOrder_State().equals("15") ){  //已完成
            viewVisibility.set(View.INVISIBLE);
            view2Visibility.set(View.INVISIBLE);
        }

        Order_OrderNo.set("订单编号：" +  productListBean.getOrder_OrderNo());

        for (OrderListBean.ProductListBean productListBeans : productListBean.getProductList()) {
            observableList.add(new OrderItemViewModel3(viewModel,productListBeans,order_id1));
        }

        initView();
    }

    private void initView() {
        subscribe = RxBus.getDefault().toObservable(String.class)
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String object){
                       if (object.equals(EventConstants.WEIXIN)){  //支付回调)
                           updorderStatus(1);
                        }
                    }
                });
        RxSubscriptions.add(subscribe);
    }


    //给RecyclerView添加ObservableList
    public ObservableList<OrderItemViewModel3> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<OrderItemViewModel3> itemBinding = ItemBinding.of(BR.viewModel, R.layout.grid_order);


    //取消订单
    public BindingCommand OnClickCommand = new BindingCommand(() -> {
        if (Order_State.get().equals("取消订单")){
            String s2 = "是否取消订单";
            new CommonDialog2(viewModel.mFragment.getActivity(), R.style.dialog, s2,"", (dialog, confirm) -> {
                if (confirm) {
                    updorderStatus(-1);
                  //  updorderStatus(3);
                }
                dialog.dismiss();
            }).show();
        }else if (Order_State.get().equals("申请退款")){

            String s2 = "是否申请退款";
            new CommonDialog2(viewModel.mFragment.getActivity(), R.style.dialog, s2,"", (dialog, confirm) -> {  //5 是退款   11 是退货
                if (confirm) {
                    Map<String, Object> params = new HashMap<>();
                    List<String> list = new ArrayList<>();
                    params.put("order_OrderNo",order_id);
                    params.put("backRemark","");
                    params.put("order_State",5);
                    params.put("imageModel",list);
                    params.put("orderItem_BackRemark","");
                    params.put("logisticsName","");
                    params.put("courierNo","");

                    HttpClient.post(viewModel.mFragment.getActivity(), Constants.BACKORDER, params,new CallBack<OrderDetailBean>() {
                        @Override
                        public void onSuccess(OrderDetailBean result) {
                            viewPagerItemViewModel.getSelorder(true);
                        }
                    });
                }
                dialog.dismiss();
            }).show();


        }else if (Order_State.get().equals("申请退货")){
            Bundle bundle = new Bundle();
            //订单号
            bundle.putString("OrderId",order_id1);
            bundle.putString("Order_OrderNo",order_id);
            viewModel.startActivity(RequestActivity.class,bundle);
            
        }else if (Order_State.get().equals("查看详情")){
            Bundle bundle = new Bundle();
            //订单号
            bundle.putString("Order_Id",order_id1);
            viewModel.startContainerActivity(MyOrderDetailsFragment.class.getCanonicalName(),bundle);

        }
    });



    //立即支付
    public BindingCommand OnClickCommand2 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (Order_pay.get().equals("待支付")){
                if (orderListBean.payType == 1){
                    Map<String, Object> params = new HashMap<>();
                    params.put("payNo",order_id);
                    params.put("userId", SPUtils.getInstance().getString(Constants.USERID));

                    HttpClient.get(viewModel.mFragment.getActivity(), Constants.ORDERPAY, params,new CallBack<PayBean>() {
                        @Override
                        public void onSuccess(PayBean result) {
                            zhiAliPay(result.getSign());
                        }
                    });

                }else {
                    Map<String, Object> params = new HashMap<>();
                    params.put("payNo",order_id);
                    params.put("userId", SPUtils.getInstance().getString(Constants.USERID));
                    HttpClient.get(viewModel.mFragment.getActivity(), Constants.ORDERPAY, params,new CallBack<WeixinBean>() {
                        @Override
                        public void onSuccess(WeixinBean weixinBean) {
                            PayReq req = new PayReq();
                            req.appId = weixinBean.getSign().getAppId();
                            req.partnerId = weixinBean.getSign().getPartnerId();
                            req.prepayId = weixinBean.getSign().getPrepayId();
                            req.nonceStr = weixinBean.getSign().getNonceStr();
                            req.timeStamp = weixinBean.getSign().getTimeStamp();
                            req.packageValue = weixinBean.getSign().getPackageValue();
                            req.sign = weixinBean.getSign().getSign();
                            //  req.extData = "0.02";
                            viewPagerItemViewModel.mWxApi.sendReq(req);
                        }
                    });
                }
            }else if (Order_pay.get().equals("确认收货")){
                //待评价
                String s2 = "是否确认收货";
                new CommonDialog2(viewModel.mFragment.getActivity(), R.style.dialog, s2,"", (dialog, confirm) -> {
                    if (confirm) {
                        updorderStatus(3);
                    }
                    dialog.dismiss();
                }).show();
            }else if (Order_pay.get().equals("去评价")){
                if (orderListBean.getProductList().size() > 1){
                    Bundle bundle = new Bundle();
                    bundle.putString("OrderId",order_id1);
                    SPUtils.getInstance().put("ping_order_id", order_id1);
                    //订单号： orderNo
                    SPUtils.getInstance().put("ping_order_No", order_id);
                    SPUtils.getInstance().put("Product_Id2","");
                    viewModel.startActivity(AppraiseXiangActivity.class,bundle);
                }else {
                    SPUtils.getInstance().put("ping_order_No", order_id);
                    Bundle bundle = new Bundle();
                    bundle.putString("OrderId",order_id1);
                    SPUtils.getInstance().put("ping_order_id", "");
                    SPUtils.getInstance().put("Product_Id2",orderListBean.getProductList().get(0).getProduct_Id());
                    viewModel.startActivity(AppraiseActivity.class,bundle);
                }
            }else if (Order_pay.get().equals("填写物流")){
                Bundle bundle = new Bundle();
                //订单号
                bundle.putString("OrderId",order_id1);
                bundle.putString("Order_OrderNo",order_id);
               viewModel.startActivity(WuLiuActivity.class,bundle);
            }
        }
    });

    private void zhiAliPay(String sign) {
        Runnable payRunnable = () -> {
            PayTask alipay = new PayTask(viewModel.mFragment.getActivity());
            PayResult payResult = new PayResult((Map<String, String>) alipay.payV2(sign, true));
            /**
             对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
             */
            final String resultStatus = payResult.getResultStatus();// 同步返回需要验证的信息
            viewModel.mFragment.getActivity().runOnUiThread(() -> {
                // 判断resultStatus 为9000则代表支付成功
                if (TextUtils.equals(resultStatus, "9000")) {
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    ToastUtil.toastShortMessage("支付成功");
                    //待发货
                    updorderStatus(1);
                } else {
                    ToastUtil.toastShortMessage("支付失败");
                }
            });
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    private void updorderStatus(int type) {
        Map<String, Object> params = new HashMap<>();
        params.put("orderNo",order_id);
        params.put("orderStatus",type + "");

        HttpClient.get(viewModel.mFragment.getActivity(), Constants.UPDORDERSTATUS, params,new CallBack<BaseBean>() {
            @Override
            public void onSuccess(BaseBean result) {
                viewPagerItemViewModel.getSelorder(true);
            }
        });
    }
}
